import { defineStore } from "pinia";
import api from "@/api/api";
import Constant from "@/utils/constant";
import messageBox from "@/utils/message";
import Cookies from "js-cookie";
import { Decrypt } from "@/utils/crypto";
import { popupNotice } from "@/api/ware.js";

export const userStore = defineStore("user", {
    state: () => ({
        userView: {},
        userPerm: {},
        bfUser: {},
        unionId: "",
        popup: {},
        wxLogin: {},
        loginModalVisible: false,
        registerType: "login",
        hasUserCount: true,
        level: 0,
        categoryClick: false,
    }),
    actions: {
        SET_CATEGORY_CLICK(payload) {
            this.categoryClick = payload;
        },
        SET_CATEGORY_LEVEL(payload) {
            this.level = payload;
        },
        SET_POPUP(payload) {
            this.popup = payload;
        },
        SET_USER_VIEW(payload) {
            this.userView = payload;
        },
        SET_USER_PERM(payload) {
            this.userPerm = payload || {};
        },
        SET_BF_USER(payload) {
            this.bfUser = payload || {};
        },
        SET_UNION_ID(payload) {
            this.unionId = payload;
        },
        SET_WX_LOGIN(payload) {
            this.wxLogin = payload;
        },
        SET_LOGIN_MODAL_VISIBLE({ visible, type = "register", path }) {
            this.loginModalVisible = visible;
            this.registerType = type;
            if (path || typeof path === "string") {
                window.sessionStorage.setItem("loginToPath", path);
            }
        },
        SET_REGISTER_TYPE(payload) {
            this.registerType = payload;
        },
        HAS_USER_COUNT(payload) {
            this.hasUserCount = payload;
        },
        // 登录
        Login(userInfo) {
            return new Promise((resolve, reject) => {
                api.UserLogin(userInfo)
                    .then(async (res) => {
                        this.SET_LOGIN_MODAL_VISIBLE({ visible: false });
                        // 设置token
                        localStorage.setItem(Constant.HttpAccessToken, res.accessToken);
                        // 为设计平台提供登录通讯
                        Cookies.set(Constant.HttpAccessToken, res.accessToken, {
                            domain: process.env.VUE_APP_DESIGN_DOMAIN,
                            expires: 365,
                        });
                        await this.GetInfo();
                        resolve();
                    })
                    .catch((error) => {
                        messageBox.error(error);
                        reject(error);
                    });
            });
        },
        getBf() {
            return new Promise(async (resolve, reject) => {
                try {
                    const res = await api.bfUser();
                    this.SET_BF_USER(res);
                    resolve();
                } catch (error) {
                    reject(error);
                }
            });
        },
        // wc登录
        WxLogin(userInfo) {
            return new Promise((resolve, reject) => {
                api.WechatCallback(userInfo)
                    .then(async (res) => {
                        if (res.flag === Constant.wechatBind) {
                            // 设置token
                            localStorage.setItem(Constant.HttpAccessToken, res.accessToken);
                            // 为设计平台提供登录通讯
                            Cookies.set(Constant.HttpAccessToken, res.accessToken, {
                                domain: process.env.VUE_APP_DESIGN_DOMAIN,
                                expires: 365,
                            });
                            await this.GetInfo();
                            const path = window.sessionStorage.getItem("loginToPath");
                            jumpToFromPath(path);
                            resolve(res);
                        } else {
                            this.SET_UNION_ID(res.unionId);
                            resolve(res);
                        }
                    })
                    .catch((err) => {
                        reject(err);
                    });
            });
        },
        // 获取用户信息
        GetInfo() {
            return new Promise(async (resolve, reject) => {
                try {
                    // 获取用户昵称
                    const userViewRes = await api.UserView();
                    this.SET_USER_VIEW(userViewRes);
                    // 设置权限
                    const userPermRes = await api.UserPerm();
                    this.SET_USER_PERM(userPermRes);
                    // 设置权限
                    const bfUserRes = await api.bfUser();
                    this.SET_BF_USER(bfUserRes);
                    // 设置权限
                    const popupRes = await popupNotice();
                    this.SET_POPUP(popupRes);

                    api.UserLoginCheck({ device: 1, token: localStorage.getItem(Constant.HttpAccessToken) })
                        .then((res) => {
                            // 可根据需要添加处理逻辑
                        })
                        .catch((err) => {
                            if (err?.indexOf("1001") > -1) {
                                setTimeout(() => {
                                    localStorage.clear();
                                    Cookies.remove(Constant.HttpAccessToken, {
                                        domain: process.env.VUE_APP_DESIGN_DOMAIN,
                                    });
                                    window.location.href = "/";
                                }, 3000);
                            } else {
                                reject(err);
                            }
                        });

                    const timer = setInterval(() => {
                        api.UserLoginCheck({ device: 1, token: localStorage.getItem(Constant.HttpAccessToken) })
                            .then((res) => {
                                // 可根据需要添加处理逻辑
                            })
                            .catch((err) => {
                                if (err?.indexOf("1001") > -1) {
                                    setTimeout(() => {
                                        localStorage.clear();
                                        Cookies.remove(Constant.HttpAccessToken, {
                                            domain: process.env.VUE_APP_DESIGN_DOMAIN,
                                        });
                                        clearInterval(timer);
                                        window.location.href = "/";
                                    }, 3000);
                                } else {
                                    clearInterval(timer);
                                    reject(err);
                                }
                            });
                    }, 2 * 60 * 1000);

                    resolve();
                } catch (error) {
                    reject(error);
                }
            });
        },
        loginCheck(i) {
            // 可根据需要添加具体逻辑
        },
        async getWeChatSetting(userInfo) {
            try {
                const res = await api.WechatSetting();
                const obj = {
                    appid: Decrypt(res.appid),
                    state: res.state,
                };
                this.SET_WX_LOGIN(obj);
            } catch (error) {
                // 可根据需要添加错误处理逻辑
            }
        },
    },
});
